/*
 * File     : AbstractLinuxPlatform.java
 * Created  : 16 Apr 2011
 *
 * Copyright © 2011 Matthew Wilson (mj. {my-surname} .uk {at} gmail.com)
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.googlecode.dni.internal.platform;

import java.nio.ByteOrder;

import com.googlecode.dni.internal.DniInternal;
import com.googlecode.dni.internal.library.DynamicLibrary;
import com.googlecode.dni.platform.PlatformGroup;
import com.googlecode.dni.platform.PlatformType;
import com.googlecode.dni.type.structure.Padding;


/**
 * <p>
 *  Implementation of {@link Platform} for GNU/Linux.
 * </p>
 *
 * @author Matthew Wilson
 */
abstract class AbstractLinuxPlatform extends AbstractPlatform
{

    /**
     * @param platformType
     *            the platform type
     * @param defaultPadding
     *            the default padding
     */
    AbstractLinuxPlatform( final PlatformType platformType, final Padding defaultPadding )
    {
        super( PlatformGroup.LINUX,
               platformType,
               DynamicLibrary.open( "libdni.so", false ),
               defaultPadding,
               getWideCharsetImpl() );
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public final String mangleLibraryName( final String name )
    {
        if ( name.contains( "/" ) || name.matches( ".*\\.so(\\.[0-9]+)*" ) )
        {
            return name;
        }

        return "lib" + name + ".so";
    }

    /** {@inheritDoc} */
    @Override
    final String getDefaultCharsetImpl()
    {
        // On Linux, the default charset is picked up from setlocale()
        String charset = PlatformUtilities.getNativeLocale();
        if ( charset == null || charset.isEmpty() )
        {
            DniInternal.LOGGER.warning( "Native locale is empty; assuming UTF-8" );
            return "UTF-8";
        }

        DniInternal.LOGGER.info( "Native charset is '" + charset + "'" );
        return charset;
    }

    private static String getWideCharsetImpl()
    {
        if ( ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN )
        {
            return "UTF-16LE";
        }

        return "UTF-16BE";
    }

}
